const Controller = require("egg").Controller;

class JwtController extends Controller{
    async index(){
        let user = {
            username: "admin"
        }
        // 用户登录生成 token 
        let token = this.app.jwt.sign(user,this.app.config.jwt.secret)
        // this.ctx.body = token

        // 每次登陆时 verify 校验 token 
        try{
            let decode = this.app.jwt.verify(token,this.app.config.jwt.secret)
            this.ctx.body = decode
        }catch(err) {
            this.ctx.body = "token验证错误"
        }
    }
    async doLogin(){
        let res = this.ctx.request.body.user;
        if(res.userName == "admin" && res.passWord == "123"){ 
            let user_jwt = {username:res.userName}
            let token = this.app.jwt.sign(res,this.app.config.jwt.secret)
            
            this.ctx.body = {
                code:200,
                token:token,
                msg:"验证通过"
            }
        }else{
            this.ctx.body = {
                code:400,
                msg:"验证未通过"
            }
        }
    }
    async getMessage(){
        let token = this.ctx.request.header.token;
        console.log(token)
        try{
            let decode = this.app.jwt.verify(token,this.app.config.jwt.secret)
            this.ctx.body = `
                hello 
                hello
                hello
                hello
            `
        }catch(err){
            this.ctx.body = "验证错误"
        }
    }
}
module.exports = JwtController